﻿using System;
using System.Linq;
using HK.Core.Common.Data;
using HK.Core.Extend;
using HK.Editor.GUIEx.Protocol.TreeView.Control;
using HK.Editor.GUIEx.Protocol.TreeView.Data;
using UnityEditor.IMGUI.Controls;

namespace HK.Editor.GUIEx.TreeView.Control
{
    /// <summary>
    /// 树形结构Element
    /// </summary>
    public class TreeViewRow<TBranch> : TreeViewItem, ITreeViewRow<TBranch>
        where TBranch : JsonData, ITreeBranch 
    {
        /// <summary>
        /// 数据
        /// </summary>
        public TBranch Data { get; set; } = null;
        
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="iId">Id</param>
        /// <param name="iDepth">深度</param>
        /// <param name="iName">Name</param>
        /// <param name="iData">数据</param>
        public TreeViewRow (int iId, int iDepth, string iName, TBranch iData) : base (iId, iDepth, iName)
        {
            Data = iData;
        }

        /// <summary>
        /// 排序子节点
        /// </summary>
        /// <param name="iSelector">排序选择器</param>
        /// <param name="iAscending">true:升序; false:降序;</param>
        /// <typeparam name="TBranch">树枝类型</typeparam>
        /// <typeparam name="TKey">Key</typeparam>
        public void SortChildren<TKey>(Func<ITreeViewRow<TBranch>, TKey> iSelector, bool iAscending)
        {
            if(!hasChildren || null == children || 1 >= children.Count) return;

            children = children
                .Cast<TreeViewRow<TBranch>>()
                .Order(iSelector, iAscending)
                .Cast<TreeViewItem>().ToList();
        }
    }
}
